package Server.Model.Hall;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;
import net.sf.json.*;
import network.handler.HandlerWrapperMgr;
import network.handler.NodeLoadMgr;
import network.handler.NodePeerMgr;
import redis.clients.jedis.Jedis;
import redis.protocal.DbInfoMgr;
import redis.protocal.UserChargeInfo;
import redis.protocal.UserRedisInfo;
import Server.Agent.GameAgent;
import Server.Agent.GameConfig;
import Server.Agent.GameDB;
import Server.Model.Base.IRoom;
import Server.Model.Base.SHMUser;
import Server.Model.Base.UserGoldChange;
import Server.Model.Hall.dthall;
import admin.AdminRedis;
import club.ClubRedis;
import common.routine.CommonZooListener;
import common.routine.GateServerChangeInfo;
import common.routine.GlobalSetting;
import common.routine.JsonUtils;
import common.routine.LogicServerChangeInfo;
import common.routine.NodeInfoVo;
import common.routine.RedisUtil;
import io.netty.channel.ChannelHandlerContext;
import common.routine.CommonDef.NodeType;
import db.Data_ninedt_user;
import tools.Sync2RedisTool;

public class ApiHandle {
	public static boolean rebooting = false;
	public static boolean reseting = false;
	public static boolean canNotify = true;
	public static List<NodeInfoVo> allLogics;
	public static List<NodeInfoVo> rebootCompleteLogics = new ArrayList<NodeInfoVo>();
	public static Map<String, String> GetRequest(String url) {
		Map<String, String> dic = new HashMap<String, String>();
		if (url.indexOf("/") != -1) {
			if (url.indexOf("?") == -1) {
				String cmd = url.substring(1);
				dic.put("cmd", cmd);
			} else {
				String cmd = url.substring(1, url.indexOf("?"));
				dic.put("cmd", cmd);
				String str = url.substring(url.indexOf("?") + 1);
				String[] strs = str.split("&");

				for (int i = 0; i < strs.length; i++) {
					String[] strs1 = strs[i].split("=");
					if (strs1.length > 1)
						dic.put(strs1[0], strs1[1]);
				}
			}
		}
		return dic;
	}
	public static String OnLogicServerReboot(String nodeInfo){
		if(nodeInfo.length() != 0)
			ApiHandle.canNotify = true;
		String rev = "";
		NodeInfoVo vo = null;
		for(int i = 0;i < ApiHandle.allLogics.size();i++){
			if(nodeInfo.equals(NodeInfoVo.getKey(ApiHandle.allLogics.get(i)))){
				vo = ApiHandle.allLogics.get(i);
				ApiHandle.allLogics.remove(i);
				break;
			}
		}
		if(vo != null){
			ApiHandle.rebootCompleteLogics.add(vo);
		}
		for(int i = 0;i < ApiHandle.rebootCompleteLogics.size();i++){
			rev += NodeInfoVo.getKey(ApiHandle.rebootCompleteLogics.get(i)) + "重启成功" + "<br>";
		}
		for(int i = 0;i < ApiHandle.allLogics.size();i++){
			rev += NodeInfoVo.getKey(ApiHandle.allLogics.get(i)) + "等待重启中" + "<br>";
		}
		if(ApiHandle.allLogics.size() == 0){
			class RebootAgainTask extends TimerTask{
				@Override
				public void run() {
					ApiHandle.rebooting = false;
					ApiHandle.reseting = false;
					ApiHandle.rebootCompleteLogics.clear();
				}
			}
			if(ApiHandle.reseting == false){
				ApiHandle.reseting = true;
				Timer timer = new Timer();
				timer.schedule(new RebootAgainTask(),120 * 1000);
				rev += "所有的逻辑服务器全部重启成功,两分钟后可以再次重启逻辑服务器,";
				//开始重启gate服务器
				class RebootGateTask extends TimerTask{
					@Override
					public void run() {
						List<NodeInfoVo> gates = CommonZooListener.getInstance().getCurrGates();
						for(int i = 0;i < gates.size();i++){
							net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
							pub.put("command","pub_request_gate_reboot");
							pub.put("value1","" + NodeInfoVo.getKey(gates.get(i)));
							AdminRedis.getInstance().pubAdminSubMsg(pub);
							System.out.println("通知gate重启" + NodeInfoVo.getKey(gates.get(i)));
						}
					}
				}
				Timer timergate = new Timer();
				timergate.schedule(new RebootGateTask(),10 * 1000);
				
				//开始重启自己
				class RebootSelfTask extends TimerTask{

					@Override
					public void run() {
						System.out.println("重启login自己了");
						System.exit(0);						
					}					
				}
				Timer timerlogin = new Timer();
				timerlogin.schedule(new RebootSelfTask(),15 * 1000);
			}else{
				rev += "所有的逻辑服务器全部重启成功,两分钟后可以再次重启逻辑服务器";
			}
		}else{
			//发布通知,至少等待30秒钟，等待logic重启注册
			if(ApiHandle.canNotify){
				ApiHandle.canNotify = false;
				class RebootNotifyTask extends TimerTask{
					@Override
					public void run() {
						if(ApiHandle.allLogics.size() > 0){
							net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
							pub.put("command","pub_request_logic_reboot");
							pub.put("value1","" + NodeInfoVo.getKey(ApiHandle.allLogics.get(0)));
							AdminRedis.getInstance().pubAdminSubMsg(pub);
							System.out.println("通知logic当机 " + System.currentTimeMillis() / 1000);
						}
						System.out.println("通知logic当机 " + System.currentTimeMillis() / 1000);
					}
				}
				Timer timer = new Timer();
				timer.schedule(new RebootNotifyTask(),30 * 1000);
				//create logic zk signal
				LogicServerChangeInfo data = new LogicServerChangeInfo();
				data._working = false;
				CommonZooListener.getInstance().setLogicNeedReboot(NodeInfoVo.getKey(ApiHandle.allLogics.get(0)),JsonUtils.serialize(data));
				System.out.println("通知gate，有logic当机 " + System.currentTimeMillis() / 1000);
			}
			System.out.println("通知gate，youlogic当机 " + System.currentTimeMillis() / 1000);
		}
		return rev;
	}
	public static String Hand(GameAgent agent ,String url,ChannelHandlerContext clientctx) {
//		url = java.net.URLDecoder.decode(url,);
		Map<String, String> dic = GetRequest(url);
		String cmd = dic.get("cmd");
		if(GlobalSetting.getInstance().getSelfNodeInfo().nodeType != NodeType.LOGIN){
			System.out.println("不是login收到消息" + "cmd=" + cmd);
			return "";
		}
		// 存储数据
		// http://127.0.0.1:9100/SaveDB
		// 添加金币
		// http://127.0.0.1:9100/AddCoin?uid=1&coin=2
		//登录
		//http://127.0.0.1:9100/hall_login?user_id=ydc1&user_nick=nic
		//创建房间
		//http://127.0.0.1:9100/hall_create_room?room_type=k510&room_param=;6JU&token=39197
		//加入房间
		//http://127.0.0.1:9100/hall_join_room?room_id=123&token=39197
		//用户掉线
		//http://127.0.0.1:9100/offline?token=123
		//前置处理
		if(cmd.equals("rebootsystemwater")){
			boolean startTask = !ApiHandle.rebooting;
			ApiHandle.rebooting = true;
			if(startTask){
				ApiHandle.allLogics = CommonZooListener.getInstance().getCurrLogics();
			}
			return ApiHandle.OnLogicServerReboot("");
		}else if(cmd.equals("reboot")){
			if(clientctx != null){
				InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
				String ip = socket.getAddress().getHostAddress();
				System.out.println("系统收到reboot消息，ip=" + ip);
			}
			return "重启操作完成,请等待";
		}else if(cmd.equals("getlogics")){
			String rev = "";
			List<String> strs = CommonZooListener.getInstance().getCurrAllLogicsNodeInfo();
			for(int i = 0;i < strs.size();i++){
				NodeInfoVo vo = JsonUtils.deserialize(strs.get(i),NodeInfoVo.class);
				if(NodeLoadMgr.getInstance().hasSuchLogicWorking(NodeInfoVo.getKey(vo))){
					rev += "逻辑服务器" + ( i + 1) + ": "+ NodeInfoVo.getKey(vo) + "<br/>";
				}
			}
			return rev;
		}else if(cmd.equals("getgates")){
			String rev = "";
			List<String> strs = CommonZooListener.getInstance().getCurrAllGatesNodeInfo();
			for(int i = 0;i < strs.size();i++){
				NodeInfoVo vo = JsonUtils.deserialize(strs.get(i),NodeInfoVo.class);
				if(NodeLoadMgr.getInstance().hasSuchGateWorking(NodeInfoVo.getKey(vo))){
					rev += "网关服务器" + ( i + 1) + ": "+ NodeInfoVo.getKey(vo) + "<br/>";
				}
			}
			return rev;
		}else if(cmd.equals("rebootlogic")){
			String node = dic.get("node");
			if(!NodeLoadMgr.getInstance().hasSuchLogicWorking(node)){
				return "找不到此逻辑服务器:" + node;
			}
			class RebootNotifyTask extends TimerTask{
				@Override
				public void run() {
					net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
					pub.put("command","pub_request_logic_reboot");
					pub.put("value1","" + node);
					AdminRedis.getInstance().pubAdminSubMsg(pub);
					System.out.println("通知logic当机 " + System.currentTimeMillis() / 1000);
				}
			}
			Timer timer = new Timer();
			timer.schedule(new RebootNotifyTask(),1000);
			return "通知成功,逻辑服务器:"  + node;
		}else if(cmd.equals("rebootgate")){
			String node = dic.get("node");
			if(!NodeLoadMgr.getInstance().hasSuchGateWorking(node)){
				return "找不到此网关服务器:" + node;
			}
			GateServerChangeInfo gateInfo = new GateServerChangeInfo();
			gateInfo._working = false;
			NodeLoadMgr.getInstance().onGateServerGetChangedInfo(node,JsonUtils.serialize(gateInfo));
			return "通知成功,网关服务器:"  + node;
		}else if(cmd.equals("logoutall")){
			if(clientctx != null){
				InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
				String ip = socket.getAddress().getHostAddress();
				System.out.println("系统收到logoutall消息，ip=" + ip);
			}
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_req_logout_all");
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "已经通知所有用户回到登录页面";
		}else if(cmd.equals("logoutuser")){
			if(clientctx != null){
				InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
				String ip = socket.getAddress().getHostAddress();
				System.out.println("系统收到logoutuser消息，ip=" + ip);
			}
			String uid = dic.get("uid");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_req_logout_user");
			pub.put("value1","" + uid);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "已经通知用户:" + uid + " 回到登录页面";
		}else if(cmd.equals("echo")){
			return "echo测试";
		}else if(cmd.equals("roomnum")){
			return "当前房间数目:" + QpGameMgr.getInstance().Handle_OnGetCurrRoomNum();
		}else if(cmd.equals("usernum")){
			return "当前在线人数:" + dthall.getInstance().Handle_OnGetCurUserNum();
		}else if(cmd.equals("playroomnum")){
			return "当前正在玩房间数目:" + QpGameMgr.getInstance().Handle_OnGetCurrPlayingRoomNum();
		}else if(cmd.equals("playusernum")){
			return "当前正在玩用户数目:" + QpGameMgr.getInstance().Handle_OnGetCurrPlayingUserNum();
		}else if(cmd.equals("getBindAgent")){
			String uid = dic.get("uid");
			return Sync2RedisTool.getInstance().getAgentBindInfo(uid);
		}else if(cmd.equals("setBindAgent")){
			String uid = dic.get("uid");
			String bind = dic.get("agent");
			return Sync2RedisTool.getInstance().setAgentBindInfo(uid,bind);
		}else if(cmd.equals("dismissroom")){
			if(clientctx != null){
				InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
				String ip = socket.getAddress().getHostAddress();
				System.out.println("系统收到dismissroom消息，ip=" + ip);
			}
			String roomid = dic.get("roomid");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_request_dismiss_room");
			pub.put("value1","" + roomid);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("dismissclub")){
			String clubid = dic.get("clubid");
			String uid = dic.get("uid");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_request_dismiss_club");
			pub.put("value1","" + clubid);
			pub.put("value2", uid);
			ClubRedis.getInstance().pubClubSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("showGongGao")){
			String text = dic.get("text");
			String type = dic.get("type");//type==1 reboot公告，type==2 世界广播，金币场需要,type==3 玩家转化，定向推送数据,跟sel数据
			String time = dic.get("time");
			if(time == null){
				time = "";
			}
			if(Integer.parseInt(type) == 10){
				type = "2";
				text += "分钟过后，系统紧急维护，请您注意时间，勿影响正常游戏";
			}
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_push_gg");
			pub.put("value1","" + type);
			pub.put("value2","" + text);
			pub.put("value3","" + time);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("removeclubroom")){
			if(clientctx != null){
				InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
				String ip = socket.getAddress().getHostAddress();
				System.out.println("系统收到removeclubroom消息，ip=" + ip);
			}

			String token = dic.get("passwd");
			if(token == null || !token.equals("ql123456789")){
				System.out.println("系统收到removeclubroom消息，但是没有密码验证！");
				return "操作完成";
			}else{
				System.out.println("密码=" + token);
			}
			
			String clubid = dic.get("clubid");
			String roomid = dic.get("roomid");
			System.out.println("clubid=" + clubid + " roomid=" + roomid);
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_remove_club_room");
			pub.put("value1","" + clubid);
			pub.put("value2","" + roomid);
			ClubRedis.getInstance().pubClubSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("cleanallclubroom")){
			if(clientctx != null){
				InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
				String ip = socket.getAddress().getHostAddress();
				System.out.println("系统收到cleanallclubroom消息，ip=" + ip);
			}
			String token = dic.get("passwd");
			if(token == null || !token.equals("ql123456789")){
				System.out.println("系统收到cleanallclubroom消息，但是没有密码验证！");
				return "操作完成";
			}else{
				System.out.println("密码=" + token);
			}
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_clean_all_club_room");
			ClubRedis.getInstance().pubClubSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("getgold")){
			String uid = dic.get("uid");
			return Sync2RedisTool.getInstance().getUserGold(uid);
		}else if(cmd.equals("getgolditem")){
			String uid = dic.get("uid");
			return Sync2RedisTool.getInstance().getUserGoldItem(uid);
		}else if(cmd.equals("addgold")){
			String uid = dic.get("uid");
			String gold = dic.get("gold");
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789"))
				return "操作完成了，但验证不对";
			return Sync2RedisTool.getInstance().addUserGold(uid,gold);
		}else if(cmd.equals("addgem")){
			String uid = dic.get("uid");
			String gem = dic.get("gem");
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789"))
				return "操作完成了，但验证不对";
			return Sync2RedisTool.getInstance().addUserGem(uid,gem);
		}else if(cmd.equals("costgolditem")){
			String uid = dic.get("uid");
			String gold = dic.get("gold");
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789"))
				return "操作完成了，但验证不对";
			return Sync2RedisTool.getInstance().costUserGoldItem(uid,gold);
		}else if(cmd.equals("useblock")){
			String use = dic.get("use");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_gate_use_block");
			pub.put("value1", use);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成use=" + use;
		}else if(cmd.equals("userankinclub")){
			String use = dic.get("use");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_logic_user_rank_inclub");
			pub.put("value1", use);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成use=" + use;
		}else if(cmd.equals("notifyisagent")){
			String uid = dic.get("uid");
			Sync2RedisTool.getInstance().notifyAsAgent(uid);
			return "设置成功";
		}else if(cmd.equals("setclubsuper")){
			String uid = dic.get("uid");
			String is = dic.get("is");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_set_super_clubuser");
			pub.put("value1", uid);
			pub.put("value2", is);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成uid=" + uid;
		}else if(cmd.equals("unblockip")){
			String ip = dic.get("ip");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_gate_unblock_ip");
			pub.put("value1", ip);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("restoreclubmem")){
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_restore_club_mem");
			pub.put("value1", "8282");
			ClubRedis.getInstance().pubClubSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("savegpsdata")){
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_save_gpsdata");
			pub.put("value1", "8282");
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成";
		}else if(cmd.equals("setAgentLevel")){
			String agentId = dic.get("agent");
			String level = dic.get("level");
			String redisData = DbInfoMgr.getInstance().getUserRedisSaveInfo(agentId);
			if(redisData == null)
				return "找不到此用户:" + agentId;
			UserRedisInfo info = JsonUtils.deserialize(redisData, UserRedisInfo.class);
			info.setGoldAgentLevel(Integer.parseInt(agentId),Integer.parseInt(level));
			DbInfoMgr.getInstance().setUserRedisSaveInfo(agentId,JsonUtils.serialize(info));
			
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_set_agent_level");
			pub.put("value1", agentId);
			pub.put("value2", level);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成level=" + level;
		}else if(cmd.equals("fenggolddwc")){
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_feng_gold_dwc");
			AdminRedis.getInstance().pubAdminSubMsg(pub);
		}else if(cmd.equals("unfenggolddwc")){
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_unfeng_gold_dwc");
			AdminRedis.getInstance().pubAdminSubMsg(pub);
		}else if(cmd.equals("setgatecpuratethreshold")){
			String cpu = dic.get("cpurate");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_gate_cpu_threshold");
			pub.put("value1", cpu);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "操作完成cpurate=" + cpu;
		}else if(cmd.equals("getusertodaycharge")){
			String uidstr = dic.get("uid");
			int uid = Integer.parseInt(uidstr);
			if(uid == 0){
				return "找不到这个用户";
			}
			String data = DbInfoMgr.getInstance().getTodayChargeKey(uid);
			if(data == null){
				return "找不到这个用户";
			}
			UserChargeInfo info = JsonUtils.deserialize(data, UserChargeInfo.class);
			return "此用户今天一共充值:" + info.money + " 得到钻石:" + info.getGem + " 得到UU:" + info.getGold;
		}else if(cmd.equals("getdaychargelimit")){
			int data = DbInfoMgr.getInstance().getUserOneDayChargeThreahold();
			return "每次充值限额:" + data;
		}else if(cmd.equals("setdaychargelimit")){
			String data = dic.get("rmb");
			int rmb = Integer.parseInt(data);
			if(rmb == 0){
				return "无效设置";
			}else{
				DbInfoMgr.getInstance().setUserOneDayChargeThreshold(rmb);
				return "每日充值限额为:" + rmb;
			}
		}else if(cmd.equals("getusergoldlog")){
			String rev = "";
			String uidstr = dic.get("uid");
			int uid = Integer.parseInt(uidstr);
			if(uid == 0)
				return "找不到此用户";
			String userDataStr = DbInfoMgr.getInstance().getUserByUid(uid);
			if(userDataStr == null){
				return "找不到此用户";
			}
			Data_ninedt_user userData = JsonUtils.deserialize(userDataStr, Data_ninedt_user.class);
			rev += "用户当前的UU豆为:" + userData.m_lTotalCoin + "<br>";
			
			List<String> alls = DbInfoMgr.getInstance().getUserGoldChangeInfo(uid);
			for(int i =alls.size() - 1;i >=0;i--){
				String data = alls.get(i);
				JSONObject json = new JSONObject(data);
				Date date = new Date(json.optLong("m_time"));
				rev += "" + date.toString() + "   before:" + json.optInt("m_before") + "  after:" + json.optInt("m_after") + "  reason:" + json.optString("m_reason") + "<br>";
			}
			return rev;
		}else if(cmd.equals("setgateconnectthreshold")){
			String connect = dic.get("connect");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_gate_connect_num");
			pub.put("value1", connect);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "设置成功:num=" + connect;
		}else if(cmd.equals("setgateselfreboottime")){
			String time = dic.get("time");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_gate_selfreboot_time");
			pub.put("value1", time);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "设置成功:time=" + time;
		}else if(cmd.equals("rebootallgate")){
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789")){
				if(clientctx != null){
					InetSocketAddress socket = (InetSocketAddress) clientctx.channel().remoteAddress();
					String ip = socket.getAddress().getHostAddress();
					System.out.println("系统收到重启所有逻辑的消息，但是密码不对，ip=" + ip);
				}
				return "设置成功";
			}
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_gate_reboot_all");
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "重启所有逻辑成功";
		}else if(cmd.equals("sendsysmail")){
			String touid = dic.get("touid");
			String title = dic.get("title");
			String content = dic.get("content");
			String gold = dic.get("gold");
			String gem = dic.get("gem");
			String game = dic.get("game");
			if(touid.isEmpty()){
				return "没有发送对象touid=";
			}
			if(title.isEmpty()){
				return "标题不能为空title=";
			}
			if(content.isEmpty()){
				return "内容不能为空content=";
			}
			if(game.isEmpty()){
				return "游戏类型不能为空game=";
			}
			//注意只有8081的可以处理这个消息
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_logic_send_mail");
			pub.put("value1", touid);
			pub.put("value2", title);
			pub.put("value3", content);
			pub.put("value4", gold);
			pub.put("value5", gem);
			pub.put("value6", game);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
		}else if(cmd.equals("binddwc")){
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789")){
				return "收到真金绑定消息，但是密码不对";
			}
			String uid = dic.get("uid");
			String agentid = dic.get("agentid");
			if(uid == null || uid.isEmpty()){
				return "收到真金绑定消息，找不到uid";
			}
			if(agentid == null || agentid.isEmpty()){
				return "收到真金绑定消息,找不到agentid";
			}
			return UserRedisInfo.bindDwcUser(Integer.parseInt(uid),Integer.parseInt(agentid));
		}else if(cmd.equals("setdwczongdai")){
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789")){
				return "收到真金设置总代，但是密码不对";
			}
			String uid = dic.get("uid");
			if(uid == null || uid.isEmpty()){
				return "收到真金设置总代，找不到uid";
			}
			return UserRedisInfo.setDwcZongDai(Integer.parseInt(uid));
		}else if(cmd.equals("regDwcUser")){
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789")){
				return "收到真金注册帐号，但是密码不对";
			}
			String tel = dic.get("tel");
			String mima = dic.get("mima");
			String name = dic.get("name");
			String agentid = dic.get("agentid");
			if(tel == null || tel.isEmpty()){
				return "收到真金注册帐号，但是手机不对";
			}
			if(mima == null || mima.isEmpty() || mima.length() < 6){
				return "收到真金注册帐号，但是密码不对";
			}
			if(name == null || name.isEmpty()){
				return "收到真金注册帐号，但是名字不对";
			}
			if(agentid == null || agentid.isEmpty()){
				return "收到真金注册帐号，代理id不对";
			}
			String hasuidcheck = DbInfoMgr.getInstance().getDwcAgentTelCheck(tel);
			if(hasuidcheck != null){
				return "收到真金注册帐号，但是手机已经被注册";
			}
			int upid = Integer.parseInt(agentid);
			String agentData = "";
			UserRedisInfo agentInfo = null;
			if(upid != 0){
				agentData = DbInfoMgr.getInstance().getUserRedisSaveInfo(agentid);
				if(agentData == null){
					return "收到真金注册帐号，找不到上级代理信息";
				}
				agentInfo = new UserRedisInfo(net.sf.json.JSONObject.fromObject(agentData));
				if(agentInfo.json.optInt("agentLevel") < 0){
					return "收到真金注册帐号，找不到上级ID不是代理";
				}
			}

			try {
				name = java.net.URLDecoder.decode(name,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//可以注册了
			Data_ninedt_user user = Sync2RedisTool.getInstance().regDwcAccountFromPhp(tel,name,mima);
			if(user != null){
				if(agentInfo != null){
					agentInfo.bindDownUser(agentInfo.json.optInt("agentLevel") + 1, user.m_lUid, name);
					DbInfoMgr.getInstance().setUserRedisSaveInfo("" + upid, agentInfo.getUserInfoStr());
				}

				DbInfoMgr.getInstance().addDwcAgentTelCheck(tel,"" + user.m_lUid);
				UserRedisInfo myInfo = new UserRedisInfo();
				myInfo.setUpAgentUid(upid);
				String headurl = GameConfig.getInstance().get("APP_HOST");
				if(!headurl.startsWith("http")){
					headurl = "http://" + headurl;
				}
				headurl += "/app/headimg/head";
				headurl += myInfo.json.optInt("headUrl");
				headurl += ".png";
				myInfo.setBasicInfo(user.m_lUid, name, headurl);
				DbInfoMgr.getInstance().setUserRedisSaveInfo("" + user.m_lUid, myInfo.getUserInfoStr());
				//设置公共的头像
				DbInfoMgr.getInstance().setUserAvatarUrl(user.m_lUid, headurl);
				return "ok";
			}else{
				return "真金帐号注册失败,可能手机号或者用户名被占用了";
			}			
		}else if(cmd.equals("dwcTelUsed")){
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789")){
				return "收到真金手机号检测，但是密码不对";
			}
			String tel = dic.get("tel");
			if(tel == null || tel.isEmpty()){
				return "收到真金手机号检测，但是手机号不存在";
			}
			String hasuidcheck = DbInfoMgr.getInstance().getDwcAgentTelCheck(tel);
			if(hasuidcheck == null){
				return "成功";
			}else{
				return "失败";
			}
		}else if(cmd.equals("haltall")){
			String passwd = dic.get("passwd");
			if(passwd == null || !passwd.equals("ql123456789")){
				return "收到停机信号，但是密码不对";
			}
			String command1 = "ps aux|grep distwatchsh.sh |grep -v grep|cut -c 9-15|xargs kill -9";
			String command2 = "ps aux|grep hn_server|grep -v grep|cut -c 9-15|xargs kill -9";
			System.out.println("准备停止系统...");
     		 try {
     			 Process process1 = Runtime.getRuntime().exec(command1);
     			 Process process2 = Runtime.getRuntime().exec(command2);
         		 return "停止成功";
     		 }catch(Exception e){
     			 
     		 }
     		return "停止失败";
		}
		
		String handStr = null;
		int uid = 0;
		try{
			String token = "";
			if(GlobalSetting.getInstance().getSelfNodeInfo().nodeType == NodeType.GATE){
				token = dic.get("token");
				ChannelHandlerContext ctx = HandlerWrapperMgr.getInstance().getHandlerChannel(token);
				if(ctx != null && cmd.equals("offline")){
					ctx.channel().close();
				}
			}else{
				token = dic.get("token");
				uid = Integer.parseInt(token);
				dthall.getInstance().linkUser(agent.getCID(), uid);
				agent.setUser(dthall.getInstance().getUserInfo(uid));
			}
		}catch(Exception e){
			
			System.out.println("token:  " + e);
		}
		switch (cmd) {
		case "fenghao":{
			String keyuid = dic.get("uid");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_feng_hao");
			pub.put("value1", keyuid);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "" + keyuid + "被封禁";
		}
		case "unfenghao":{
			String keyuid = dic.get("uid");
			net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
			pub.put("command","public_un_feng_hao");
			pub.put("value1", keyuid);
			AdminRedis.getInstance().pubAdminSubMsg(pub);
			return "" + keyuid + "被解禁";
		}
		case "diaoxianall":{
			HandlerWrapperMgr.getInstance().closeAllChannelHandler();
			return "全部掉线";
		}
		case "diaoxianuser":{
			String user = dic.get("uid");
			HandlerWrapperMgr.getInstance().closeUserChannelHandler(user);
			return "用户掉线";
		}
		case "offline":{
			dthall.getInstance().Handle_OnUserOffline(uid);
			return "用户:" + uid + "已经掉线";
		}
		case "AddCoin": {// 此处加金币没有即刻通知客户端
			uid = Integer.parseInt(dic.get("uid"));
			int coin = Integer.parseInt(dic.get("coin"));
			handStr = AddCoin(uid, coin);
			
			
			return "添加成功";
		}
		case "SaveDB":
			//GameDB.getInstance().deal_delay_save(0);
			handStr = "SaveDB";
			break;
		case "hall_login":
		{
			break;
		}
		case "hall_create_room":
		{
			JSONObject root = new JSONObject();
			root.put("command", "hall_create_room");
			root.put("room_type", dic.get("room_type"));
			root.put("room_param", dic.get("room_param"));
			root.put("room_fg", dic.get("room_fg"));
			//handStr = dthall.getInstance().Handle_OnCreateRoom_Http(agent.getUid(), root);
			break;
		}
		case "hall_join_room":
		{
			JSONObject root = new JSONObject();
			root.put("command", "hall_join_room");
			root.put("room_id", dic.get("room_id"));
			//handStr = dthall.getInstance().Handle_OnJoinRoom_Http(agent.getUid(), root);
			break;
		}
		case "hall_get_rooms":
		{
			//handStr = dthall.getInstance().onDealFangGuanGetRoomList_HTTP(agent.getUid());
			break;
		}
		case "hall_room_info":
		{
			IRoom tbl = null;
			if (dic.containsKey("room_id")) {
				 int room_id = Integer.parseInt(dic.get("room_id"));
				 if (QpGameMgr.getInstance().m_mapRoom.containsKey(room_id)) {
					 tbl = QpGameMgr.getInstance().m_mapRoom.get(room_id);
				}
			}else{
				if (QpGameMgr.getInstance().m_mapUserRoom.containsKey(uid)) {
					 tbl = QpGameMgr.getInstance().m_mapUserRoom.get(uid);
				}
			}
			if(tbl != null){
				//handStr = tbl.getRoomInfoJson();
			}
			else{
				handStr = "房间已解散";
			}
			break;
		}	
		case "gonggao":
		{
			//dthall.getInstance().onDealSaveGongGao();
			break;
		}			
		default:
			break;
		}
		if(handStr != null &&  dic.containsKey("callBack")){
			String callBack = dic.get("callBack");
			handStr = callBack+"(\""+handStr.replace("\"","\\\"") +"\")";
		}
		return handStr;
	}

	public static String AddCoin(int uid, int coin) {
		SHMUser user = dthall.getInstance().getUserInfo(uid);
		if (user != null) {
			if (coin > 0) {
				user.getCoin(coin);
				//return "ok  nickname" + user.getNickName() + " now coin: "	+ user.getCoin(0);
			}
		}
		return "用户不存在 或者 金币为负";
	}
}
